﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using DHQGHN.PM2.Security;
using System.Web.Helpers;
using System.Web.Routing;
using DHQGHN.PM2.Models;

namespace DHQGHN.PM2.Controllers
{
    public class BaseController : Controller
    {
        protected const int PageSize = 10;
        //phunx1, 20150609: lay thong tin chung cua User
        protected virtual MyPrincipal MyUser
        {
            get { return HttpContext.User as MyPrincipal; }
        }

        protected string AppTime = DateTime.Now.Ticks.ToString();
        public BaseController()
        {
            ViewBag.AppTime = AppTime;
        }

        // quang:
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext == null)
            {
                return;
            }
            base.OnActionExecuting(filterContext);
            if (!"Login".Equals(filterContext.ActionDescriptor.ActionName) && !"LoginKhaiOnline".Equals(filterContext.ActionDescriptor.ActionName))
            {
                //if (Session["UserInfo"] == null)
                if (Session["MenuUrl"] == null)
                {
                    if (!"SignOut".Equals(filterContext.ActionDescriptor.ActionName))
                    {
                        RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
                        redirectTargetDictionary.Add("action", "SignOut");
                        redirectTargetDictionary.Add("controller", "Account");
                        filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
                    }
                }
                /* Quang: 20150729
                 * kiem rta xem action dang duoc chon den co trong danh sach actionname ma user co quyen truy cap den
                 * co the ket hop de kiem tra xem user nay da dang nhap truoc do hay chua 
                 */
                //else
                //{
                //    if (!Session["AuthToken"].ToString().Equals(Request.Cookies["AuthToken"].Value))
                //    {
                //        //filterContext.Result = new RedirectResult("/Account/Login");
                //        RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
                //        redirectTargetDictionary.Add("action", "Login");
                //        redirectTargetDictionary.Add("controller", "Account");
                //        filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
                //    }
                //    else if (!Request.IsAjaxRequest())
                //    {
                //        string url = GetUrl(filterContext.ActionDescriptor);
                //        if (!IsPermiss(url))
                //        {
                //            RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
                //            redirectTargetDictionary.Add("action", "NotAuthorized");
                //            redirectTargetDictionary.Add("controller", "Account");
                //            filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
                //        }
                //    }
                //}

            }
        }

        /// Quang: 20150729 : Ham check xem user co actionname ko
        /// 
        private bool IsPermiss(string AN)
        {
            List<string> roles = Session["MenuUrl"] as List<string>;
            if (roles == null)
                return false;
            if (AN.Contains("/BaoCao/")){
                return true;
            }

            return roles.Contains(AN);


            //if (MyUser == null)
            //    return false;
            //if (MyUser.Roles != null)
            //    return MyUser.Roles.Contains(AN);

            //return false;
        }

        private string GetUrl(ActionDescriptor actionDescriptor)
        {
            string url = "/" + actionDescriptor.ControllerDescriptor.ControllerName + "/" + actionDescriptor.ActionName;
            return url;
        }

        /// <summary>
        /// nguoi tao: tribh
        /// muc dich: check time out
        /// </summary>
        /// <param name="timeOut">time out check s</param>
        /// <returns></returns>
        public bool CheckTimeOut()
        {
            bool checkTimeOut = true;
            //DateTime? timeOutLocal = DateTime.Now.AddSeconds(timeOut);
            if (HttpContext.Session["LoginTimeOutOnline"] == null)
            {
                checkTimeOut = false;

            }
            HttpContext.Session.Add("LoginTimeOutOnline", DateTime.Now);
            return checkTimeOut;
            //return 1;

        }

        //internal IEnumerable<SelectListItem> GetMasterListByName(string tablename)
        //{
        //    List<DHQGHN.PM2.Models.MasterListModel> lst = new List<DHQGHN.PM2.Models.MasterListModel>();
        //    //EthnicModels.Add(new EthnicModel() { CODE = 1, ETHNIC_ID });          
        //    using (System.Net.WebClient wc = new System.Net.WebClient())
        //    {
        //        wc.Encoding = System.Text.Encoding.UTF8;
        //        // List<SelectListItem> lstItems = new List<SelectListItem>();

        //        string ethnicDownload = wc.DownloadString(masterListServiceUrl + "GetAllByListName" + "/" + tablename);
        //        lst = Newtonsoft.Json.JsonConvert.DeserializeObjectAsync<List<DHQGHN.PM2.Models.MasterListModel>>(ethnicDownload).Result;
        //        IList<SelectListItem> lstItem = new List<SelectListItem>();
        //        lstItem.Add(new SelectListItem() { Selected = false, Value = string.Empty, Text = "--Chọn giá trị--" });
        //        for (int i = 0; i < lst.Count; i++)
        //        {
        //            SelectListItem item = new SelectListItem();
        //            item.Selected = false;
        //            item.Text = lst[i].Name;
        //            item.Value = lst[i].CodeID;
        //            lstItem.Add(item);
        //        }
        //        return lstItem;
        //    }
        //}
        //public JsonResult GetAllByListName(string tablename)
        //{
        //    List<DHQGHN.PM2.Models.MasterListModel> lst = new List<DHQGHN.PM2.Models.MasterListModel>();
        //    //EthnicModels.Add(new EthnicModel() { CODE = 1, ETHNIC_ID });          
        //    using (System.Net.WebClient wc = new System.Net.WebClient())
        //    {
        //        wc.Encoding = System.Text.Encoding.UTF8;
        //        // List<SelectListItem> lstItems = new List<SelectListItem>();

        //        string ethnicDownload = wc.DownloadString(masterListServiceUrl + "GetAllByListName" + "/" + tablename);
        //        lst = Newtonsoft.Json.JsonConvert.DeserializeObjectAsync<List<DHQGHN.PM2.Models.MasterListModel>>(ethnicDownload).Result;
        //        return Json(lst, JsonRequestBehavior.AllowGet);
        //    }

        //}

        /// <summary>
        /// nguoi tao: DatLQ
        /// muc dich: Check An toan thong tin (Cross-site  request  forgery)
        /// Su dung nhu Webhelper [AjaxValidateAntiForgeryToken]
        /// </summary>
        /// <param name="AjaxValidateAntiForgeryToken">AjaxValidateAntiForgeryToken</param>
        /// <returns></returns>
        [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
        public class AjaxValidateAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
        {
            public void OnAuthorization(AuthorizationContext filterContext)
            {
                try
                {
                    if (filterContext == null)
                    {
                        return;
                    }
                    if (filterContext.HttpContext.Request.IsAjaxRequest()) // if it is ajax request.
                    {
                        this.ValidateRequestHeader(filterContext.HttpContext.Request); // run the validation.
                    }
                    else
                    {
                        AntiForgery.Validate();
                    }
                }
                catch (HttpAntiForgeryException e)
                {
                    throw new HttpAntiForgeryException("Anti forgery token not found");
                }
            }

            private void ValidateRequestHeader(HttpRequestBase request)
            {
                string cookieToken = string.Empty;
                string formToken = string.Empty;
                string tokenValue = request.Headers["VerificationToken"]; // read the header key and validate the tokens.
                if (!string.IsNullOrEmpty(tokenValue))
                {
                    string[] tokens = tokenValue.Split(',');
                    if (tokens.Length == 2)
                    {
                        cookieToken = tokens[0].Trim();
                        formToken = tokens[1].Trim();
                    }
                }

                AntiForgery.Validate(cookieToken, formToken); // this validates the request token.
            }
        }

        protected string GetAccountLogin()
        {
            string accountLogin = string.Empty;
            if (Session["NguoiDungInfo"] != null)
            {
                DHQGHN.PM2.Models.DHQG.NguoiDungModel userInfo = Session["NguoiDungInfo"] as DHQGHN.PM2.Models.DHQG.NguoiDungModel;

                if (userInfo != null)
                {
                    accountLogin = userInfo.TAI_KHOAN;
                }
            }

            return accountLogin;
        }

        protected DHQGHN.PM2.Models.DHQG.NguoiDungModel GetNguoiDungInfo()
        {
            DHQGHN.PM2.Models.DHQG.NguoiDungModel userInfo = null;
            if (Session["NguoiDungInfo"] != null)
            {
                userInfo = Session["NguoiDungInfo"] as DHQGHN.PM2.Models.DHQG.NguoiDungModel;
            }

            return userInfo;
        }

        protected DonViModel GetDonViModel()
        {
            DonViModel model = null;
            if (Session["NguoiDungInfo"] != null)
            {
                DHQGHN.PM2.Models.DHQG.NguoiDungModel userInfo = Session["NguoiDungInfo"] as DHQGHN.PM2.Models.DHQG.NguoiDungModel;

                if (userInfo != null)
                {
                    if (userInfo.listDonVi != null && userInfo.listDonVi.Count > 0)
                    {
                        model = userInfo.listDonVi[0];
                    }
                }
            }

            return model;
        }
    }
}
